package breakout2014;

import com.jme3.app.SimpleApplication;
import com.jme3.asset.AssetNotFoundException;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LevelFactoryLoader {

    private static final Logger logger = Logger.getLogger(LevelFactoryLoader.class.getName());
    private SimpleApplication context;
    private SpatialFactory spatialFactory;
    
    public LevelFactoryLoader(SimpleApplication context) {
        Logger.getLogger(LevelFactoryLoader.class.getName()).setLevel(Level.INFO); // SEVERE  INFO
        this.context = context;
        spatialFactory = new SpatialFactory (context);
        context.getAssetManager().registerLoader(TextLoader.class, "inv");
        context.getAssetManager().registerLoader(TextLoader.class, "lvl");
    }
    
    public boolean buildLevel(String levelName, Node root) {
        logger.log(Level.INFO, "buildLevel: {0}", new Object[]{levelName});
        Map<String,String> elementMap=new HashMap<String, String>();
        String levelDescriberTxt;
        try {
            levelDescriberTxt =  (String)context.getAssetManager().loadAsset("Levels/" + levelName + ".lvl");
        }
        catch (AssetNotFoundException e){
            logger.log(Level.WARNING, "Exception while loading level asset: {0}", new Object[]{e});
            return false;
        }
        catch (IllegalStateException e){
            logger.log(Level.WARNING, "Exception while loading level asset: {0}", new Object[]{e});
            return false;
        }
        
        // Create key, value map of the content of the level describer text
        elementMap.clear();
        Scanner describerScanner = new Scanner(levelDescriberTxt);
        while (describerScanner.hasNext()){
           String line = describerScanner.next();
           int index = line.indexOf(":");
           if (index != 0){
               String key = line.substring(0, index);
               String value = line.substring(index+1);
               elementMap.put(key, value );
           }
        }
        buildEmptyLevel(root);
        buildBricks(elementMap, root);
        return true;
    }
    
    // create only the parent nodes but without children
    public void buildEmptyLevel(Node root) {
        Node bricks = new Node("bricks");
        root.attachChild(bricks);
    }

    private void buildBricks(Map elementMap, Node root) {
        try{
            Node bricks = (Node)root.getChild("bricks");
            Object objTotBricks = elementMap.get("TotalBricks");
            if (objTotBricks == null) {
                logger.log(Level.WARNING, "Error: TotalBricks key not found!!", new Object[]{});
                return;
            }
            int totalBricks = Integer.parseInt((String)objTotBricks);
            for(int index = 0; index < totalBricks; index++){
                Spatial child = spatialFactory.buildSpatial((String)elementMap.get("Brick_" + index + "_Type"));
                float posX = Float.parseFloat((String)elementMap.get("Brick_" + index + "_PosX"));
                float posY = Float.parseFloat((String)elementMap.get("Brick_" + index + "_PosY"));
                child.setLocalTranslation(posX, posY, 0);
                bricks.attachChild(child);
            }
        }        
        catch (NullPointerException e){
            logger.log(Level.WARNING, "Exception error in parsing brick description", new Object[]{});
        }
    }
}
